const mysql = require('mysql2/promise');

// 创建数据库连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'wang6688',
    database: 'pet_mall',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 获取所有商品
async function getAllProducts() {
    const [rows] = await pool.execute('SELECT * FROM products');
    return rows;
}

// 根据 ID 获取商品
async function getProductById(id) {
    const [rows] = await pool.execute('SELECT * FROM products WHERE id = ?', [id]);
    return rows[0];
}

// 创建商品
async function createProduct(name, price, description) {
    const [result] = await pool.execute('INSERT INTO products (name, price, description) VALUES (?,?,?)', [name, price, description]);
    return result.insertId;
}

// 更新商品
async function updateProduct(id, name, price, description) {
    const [result] = await pool.execute('UPDATE products SET name = ?, price = ?, description = ? WHERE id = ?', [name, price, description, id]);
    return result.affectedRows;
}

// 删除商品
async function deleteProduct(id) {
    const [result] = await pool.execute('DELETE FROM products WHERE id = ?', [id]);
    return result.affectedRows;
}

module.exports = {
    getAllProducts,
    getProductById,
    createProduct,
    updateProduct,
    deleteProduct
};